package com.example.vfu_telia;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;

public class RotationDirection implements SensorEventListener {

	private SensorManager mSensMan; 
    private float mAzimuth; 
    private float[] mGravs = new float[3]; 
    private float[] mGeoMags = new float[3]; 
    private float[] mOrientation = new float[3]; 
    private float[] mRotationM = new float[9]; 
    private boolean mFailed; 
    
    public String getAzimuthString(){
    	String ret = Float.toString(mAzimuth);
    	return ret;
    }
    
    public int getAzimuthInt(){
    	int ret = (int) mAzimuth;
    	return ret;
    }
    
    public RotationDirection(Context context){
    	
    	mSensMan = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); 
    	regSensors();
    }
    
    public void regSensors(){
    	mSensMan.registerListener(this, mSensMan.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_UI); 
        mSensMan.registerListener(this, mSensMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
    }
    
    public void unRegSensors(){
    	mSensMan.unregisterListener(this);
    }

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO RotationDirection/onAccuracyChanged -Ignore for now
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		switch (event.sensor.getType()) { 
        case Sensor.TYPE_ACCELEROMETER:
                System.arraycopy(event.values, 0, mGravs, 0, 3); 
                break; 
        case Sensor.TYPE_MAGNETIC_FIELD:
                for (int i=0;i<3;i++) mGeoMags[i] = event.values[i]; 
                break; 
        	default: 
        		return; 
        } 

        if (SensorManager.getRotationMatrix(mRotationM, null, mGravs, mGeoMags)){  
                SensorManager.getOrientation(mRotationM, mOrientation); 
                onSuccess(); 
        } 
        else onFailure(); 
	} 

	void onSuccess(){ 
        if (mFailed) mFailed = false; 
        mAzimuth = (float) Math.round((Math.toDegrees(mOrientation[0])));
        mAzimuth = (mAzimuth+360)%360;
} 

	void onFailure() { 
        if (!mFailed) { 
                mFailed = true; 
        } 
	}
}
